package com.xiaoman.jvm.classpath.impl;

import com.xiaoman.jvm.classpath.Entry;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CompositeEntry implements Entry {
    private final List<Entry> entryList = new ArrayList<>();
    public CompositeEntry(String pathList) {
        String[] paths = pathList.split(File.pathSeparator);
        for (String path : paths) {
            entryList.add(Entry.newEntry(path));
        }
    }

    /**
     * 依次调用每一个子路径的readClass（）方法，如果成功读取到class数据，返回数据即可；如果收到错误信息，则继续；如果遍历完所有的子路径还没有找到class文件，则返回错误
     *
     * @param className class文件的相对路径，路径之间用斜线（/）分隔，文件名有.class后缀
     * @return
     * @throws IOException
     */
    @Override
    public byte[] readClass(String className) throws IOException {
        for (Entry entry : entryList) {
            try {
                return entry.readClass(className);
            } catch (Exception ignored) {
                //ignored
            }
        }
        throw new IOException("class not found " + className);
    }

    /**
     * 调用每一个子路径的String（）方法，然后把得到的字符串用路径分隔符拼接起来即可
     * @return
     */
    @Override
    public String String() {
        String[] strs = new String[entryList.size()];
        for (int i = 0; i < entryList.size(); i++) {
            strs[i] = entryList.get(i).toString();
        }
        return String.join(File.pathSeparator, strs);
    }
}
